<template>
    <div class="dialog-form">
        <div class="form-password">
            <el-form :label-position="'right'" ref="passwordForm" label-width="100px" :model="oPasswordInfo" :rules="oPasswordRules">
                <el-form-item  label="原密码:" prop="oldPassword">
                    <el-input type="password" placeholder="请输入原密码！" v-model="oPasswordInfo.oldPassword"></el-input>
                </el-form-item>
                <el-form-item  label="新密码:" prop="password">
                    <el-input type="password" placeholder="新密码由8~12位字母数字组成！" v-model="oPasswordInfo.password"></el-input>
                </el-form-item>
                <el-form-item label="确认新密码:" prop="confirmPassword">
                    <el-input type="password" placeholder="确认密码与新密码要一致！" v-model="oPasswordInfo.confirmPassword"></el-input>
                </el-form-item>
            </el-form>
            <el-row type="flex" align="middle">
                <el-col :span="24" style="text-align:center">
                    <el-button  class="ui button primary" @click="fnDialogClose(passwordForm)">取 消</el-button>
                    <el-button class="ui button primary" @click="fnDialogConfirm(passwordForm)">确 认</el-button>
                </el-col>
            </el-row>
        </div>
        <div class="password-rules">
            <span class="title">密码使用规则：</span>
            <div class="rules-content">
                <span v-for="(item, index) in passwordRules" :key="index">{{index+1 + '.' + item.content}}</span>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
    import {reactive,ref} from 'vue'
    import {ElMessage,FormInstance} from "element-plus";
    import {useDataStore} from "@/store/data";
    import {storeToRefs} from "pinia";
    import Crypto from "@/assets/Crypto";
    import {sm4encode} from "@/utils/sm4Util";
    import {changePassword} from "@/api";
    import  CryptoJS from "@/home/core-sha256"
    import md5 from "@/home/md5"

    const oPasswordInfo=reactive({
        password:"",
        oldPassword:"",
        confirmPassword:""
    })
    const dataStore=useDataStore();
    const {username}=storeToRefs(dataStore)
    const passwordForm=ref<FormInstance>()
    const tokenId=localStorage.getItem('tokenId')
    // const md5:any=new URL('../../home/md5.js',import.meta.url).href
    const cry:any=new Crypto();
    const oValidator = {
        validateNewPassword: function (rule:any, value:any, callback:any) {
            var reg = new RegExp(
                /(?=^.{8,12}$)(?=(?:.*?\d){1})(?=.*[a-z])(?=(?:.*?[A-Z]){1})(?=(?:.*?[!@#$%*()_+^&}{:;?.]){1})(?!.*\s)[0-9a-zA-Z!@#$%*()_+^&]*$/
            );
            if (!reg.test(value)) {
                callback(new Error("请按规则输入密码！"));
            } else if (value === oPasswordInfo.oldPassword) {
                callback(new Error("新密码不能与原密码相同！"));
            } else if (value === "用户名") {
                callback(new Error("密码不能与用户名相同！"));
            } else {
                callback();
            }
        },
        validateOldPassword: function (rule:any, value:any, callback:any) {
            if (value === oPasswordInfo.password) {
                callback(new Error("新密码不能与原密码相同！"));
            } else {
                callback();
            }
        },
        validateConfirmPassword: function (rule:any, value:any, callback:any) {
            if (value !== oPasswordInfo.password) {
                callback(new Error("确认密码与新密码要一致！"));
            } else {
                callback();
            }
        }
    };
    const oPasswordRules=reactive({
        password: [
            {required: true, message: "请输入新密码！", trigger: "blur"},
            {validator: oValidator.validateNewPassword, trigger: "blur"}
        ],
        oldPassword: [
            {required: true, message: "请输入原始密码！", trigger: "blur"},
            {validator: oValidator.validateOldPassword, trigger: "blur"}
        ],
        confirmPassword: [
            {required: true, message: "请输入确认密码！", trigger: "blur"},
            {validator: oValidator.validateConfirmPassword, trigger: "blur"}
        ]
    })
    const passwordRules=reactive([
        {content: "密码长度必须在8位与12位之间"},
        {content: "密码要包含大写字母、小写字母、数字和特殊字符"},
        {content: "密码至少每6个月更换一次"},
        {content: "密码禁止使用前一次的密码"},
        {content: "密码不能与用户名相同"}
    ])
    //取消按钮
    const fnDialogClose = (formEl: FormInstance | undefined) => {
            if (!formEl) return
            formEl.resetFields()
    }
    //确认按钮
    const fnDialogConfirm=(formEl: FormInstance | undefined)=>{
        if (!formEl) return
        formEl.validate((valid) => {
            if (valid) {
                const userCode=dataStore.$patch({
                    username
                })
                const oldPassword=CryptoJS(oPasswordInfo.oldPassword+userCode)
                const newPassword=CryptoJS(oPasswordInfo.password+userCode)
                const up_data="oldPassword="+sm4encode(JSON.stringify(oldPassword))+"&newPassword="+sm4encode(JSON.stringify(newPassword))+"&userName="+userCode+"&userCode="+userCode
                const config={
                    headers:{
                        "safe":(localStorage.getItem('safeFlag')&&JSON.parse(localStorage.getItem('safeFlag')||'{}'))?'safe':'unsafe',
                        "MD5":(localStorage.getItem('safeFlag')&&JSON.parse(localStorage.getItem('safeFlag')||'{}'))?md5(up_data+'4%YKW!@g5LGcf9Ut'):''
                    }
                }
                changePassword(up_data,{headers:config.headers}).then(res=>{
                    let da=res
                    if(localStorage.getItem('safeFlag')&&JSON.parse(localStorage.getItem('safeFlag')||'{}')&&typeof res==="string"){
                        da=da.replace(/[\r\n]/g,"");
                        da=cry.encrypt(da)
                    }
                    if(!da){
                        ElMessage.error('修改密码失败')
                    }
                }).catch(err=>{
                    ElMessage.error('修改密码失败')
                })
            } else {
                console.log('error submit!')
                return false
            }
        })
    }
</script>

<style  scoped>
    @import "/src/css/resetPassword.css";
</style>
